<template>
  <el-container class="home">
    <!--头部行-->
    <el-header style="padding: 0px;margin: 10px 10px 10px 10px;">
      <!--头部行-->
      <el-row class="headerRow" style="padding: 15px;">
        <!--初始化设计器-->
        <el-col :span="3" style="text-align: center;">
          <el-button type="info" plain @click="initDesignBtn" size="mini">初始化设计器</el-button>
        </el-col>
        <!--业务数据-->
        <el-col :span="18">
          <el-form
            label-width="100px"
            size="mini"
          >
            <el-row>
              <!--英文名-->
              <el-col :span="8">
                <el-form-item label="英文名:" size="mini" style="margin-bottom: 0px;" required>
                  <el-input v-model='form.name'></el-input>
                </el-form-item>
              </el-col>
              <!--流程名-->
              <el-col :span="8">
                <el-form-item label="中文名:" style="margin-bottom: 0px;" required>
                  <el-input v-model='form.displayName'></el-input>
                </el-form-item>
              </el-col>
              <!--流程类型-->
              <el-col :span="8">
                <el-form-item label="流程类型:" style="margin-bottom: 0px;" required>
                  <el-select
                    v-model="form.processType"
                    filterable
                    clearable
                    placeholder="--请选择--"
                  >
                    <el-option
                      v-for="(value,key,index) in dict.processType"
                      :key="index"
                      :label="value"
                      :value="key"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
        <!--保存-->
        <el-col :span="3" style="text-align: center;">
          <el-button type="success" @click="addBean" size="mini">保存</el-button>
        </el-col>
      </el-row>
    </el-header>
    <el-container>
      <!--工具栏-->
      <el-aside style="margin: 10px 0px 0px 10px;overflow: visible;" width="240px">
        <el-row class="headerRow">
          <div class="panel-body icon-list" process-type="startevent-none">开始</div>
          <div class="panel-body icon-list" process-type="gateway-exclusive">唯一网关</div>
          <div class="panel-body icon-list" process-type="gateway-fork">并行网关</div>
          <div class="panel-body icon-list" process-type="gateway-join">合并网关</div>
          <div class="panel-body icon-list" process-type="endevent-none">结束</div>
          <!--不用取消节点，直接拒绝即可-->
          <div style="position: absolute; height: 100%"></div>
        </el-row>
        <el-row class="activityRow" style="height: 25px;">活动</el-row>
        <el-row class="headerRow">
          <div class="panel-body icon-list task" process-type="task">任务</div>
        </el-row>
      </el-aside>
      <!--字体内容-->
      <el-container>
        <!--画布-->
        <el-main style="padding: 10px 10px 0px 10px;">
          <el-row class="headerRow diagram-container" style="border: none;">
            <!--画布-->
            <div
              id="canvas"
              class="wf_canvas"
              style="height: 250px;">
            </div>
          </el-row>
        </el-main>
        <!--属性-->
        <el-footer class="headerRow attr-footer" style="height: 230px;margin: 0px 10px 0px 10px;padding: 0px;">
          <!--属性-->
          <el-row class="activityRow" style="height: 25px;border: none;">属性</el-row>
          <!--根据不同的流程组件显示不同的表单，变量不要公用,属性变化自动保存内容到data中-->
          <el-form
            label-width="130px"
            size="mini"
            :model="attr.ruleSelect"
            ref="attrForm"
          >
            <!--起始节点-->
            <el-row v-if="attr.modelShow === 'startevent-none'" class="attr-row-class">
              <!--名称-->
              <el-col :span="8">
                <el-form-item label="名称:" prop="name" :rules="attr.formRules.name">
                  <el-input v-model='attr["startevent-none-form"].name' name="name"></el-input>
                </el-form-item>
              </el-col>
              <!--前置拦截器-->
              <el-col :span="8" class="not_pre">
                <el-form-item label="前置拦截器:">
                  <el-input v-model='attr["startevent-none-form"].preInterceptor' name="preInterceptor"></el-input>
                </el-form-item>
              </el-col>
              <!--任务拦截器-->
              <el-col :span="8">
                <el-form-item label="任务拦截器:">
                  <el-input v-model='attr["startevent-none-form"].postInterceptors' name="postInterceptors"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--结束节点-->
            <el-row v-if="attr.modelShow === 'endevent-none'" class="attr-row-class">
              <!--名称-->
              <el-col :span="8">
                <el-form-item label="名称:" prop="name" :rules="attr.formRules.name">
                  <el-input v-model='attr["endevent-none-form"].name' name="name"></el-input>
                </el-form-item>
              </el-col>
              <!--前置拦截器-->
              <el-col :span="8" class="not_pre">
                <el-form-item label="前置拦截器:">
                  <el-input v-model='attr["endevent-none-form"].preInterceptor' name="preInterceptor"></el-input>
                </el-form-item>
              </el-col>
              <!--任务拦截器-->
              <el-col :span="8">
                <el-form-item label="任务拦截器:">
                  <el-input v-model='attr["endevent-none-form"].postInterceptors' name="postInterceptors"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--任务节点-->
            <el-row v-if="attr.modelShow === 'task'" class="attr-row-class">
              <!--名称-->
              <el-col :span="8">
                <el-form-item label="名称:" prop='name' :rules="attr.formRules.name">
                  <el-input v-model='attr["task-form"].name' name="name"></el-input>
                </el-form-item>
              </el-col>
              <!--显示名称-->
              <el-col :span="8">
                <el-form-item label="显示名称:" prop='displayName' :rules="attr.formRules.displayName">
                  <el-input v-model='attr["task-form"].displayName' name="displayName"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--唯一网关-->
            <el-row v-if="attr.modelShow === 'gateway-exclusive'" class="attr-row-class">
              <!--名称-->
              <el-col :span="8">
                <el-form-item label="名称:" prop="name" :rules="attr.formRules.name">
                  <el-input v-model='attr["gateway-exclusive-form"].form.name' name="name"></el-input>
                </el-form-item>
              </el-col>
              <!--决策处理器接口-->
              <el-col :span="8">
                <el-form-item label="决策处理器接口:">
                  <el-input v-model='attr["gateway-exclusive-form"].decisionHandler' name="decisionHandler"></el-input>
                </el-form-item>
              </el-col>
              <!--前置拦截器-->
              <el-col :span="8" class="not_pre">
                <el-form-item label="前置拦截器:">
                  <el-input v-model='attr["gateway-exclusive-form"].preInterceptor' name="preInterceptor"></el-input>
                </el-form-item>
              </el-col>
              <!--任务拦截器-->
              <el-col :span="8">
                <el-form-item label="任务拦截器:" style="margin-bottom: 0px;">
                  <el-input v-model='attr["gateway-exclusive-form"].postInterceptors' name="postInterceptors"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--并行网关-->
            <el-row v-if="attr.modelShow === 'gateway-fork'" class="attr-row-class">
              <!--名称-->
              <el-col :span="8">
                <el-form-item label="名称:" prop="name" :rules="attr.formRules.name">
                  <el-input v-model='attr["gateway-fork-form"].name' name="name"></el-input>
                </el-form-item>
              </el-col>
              <!--前置拦截器-->
              <el-col :span="8" class="not_pre">
                <el-form-item label="前置拦截器:">
                  <el-input v-model='attr["gateway-fork-form"].preInterceptor' name="preInterceptor"></el-input>
                </el-form-item>
              </el-col>
              <!--任务拦截器-->
              <el-col :span="8">
                <el-form-item label="任务拦截器:">
                  <el-input v-model='attr["gateway-fork-form"].postInterceptors' name="postInterceptors"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--合并网关-->
            <el-row v-if="attr.modelShow === 'gateway-join'" class="attr-row-class">
              <!--名称-->
              <el-col :span="8">
                <el-form-item label="名称:" prop="name" :rules="attr.formRules.name">
                  <el-input v-model='attr["gateway-join-form"].name' name="name"></el-input>
                </el-form-item>
              </el-col>
              <!--前置拦截器-->
              <el-col :span="8" class="not_pre">
                <el-form-item label="前置拦截器:">
                  <el-input v-model='attr["gateway-join-form"].preInterceptor' name="preInterceptor"></el-input>
                </el-form-item>
              </el-col>
              <!--任务拦截器-->
              <el-col :span="8">
                <el-form-item label="任务拦截器:">
                  <el-input v-model='attr["gateway-join-form"].postInterceptors' name="postInterceptors"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--连接-->
            <el-row v-if="attr.modelShow === 'connection'" class="attr-row-class">
              <!--名称-->
              <el-col :span="8">
                <el-form-item label="名称:" prop="name" :rules="attr.formRules.name">
                  <el-input v-model='attr["connection-form"].name' name="name"></el-input>
                </el-form-item>
              </el-col>
              <!--显示名称-->
              <el-col :span="8">
                <el-form-item label="显示名称:">
                  <el-input v-model='attr["connection-form"].displayName' name="displayName"></el-input>
                </el-form-item>
              </el-col>
              <!--条件表达式-->
              <el-col :span="12">
                <el-form-item label="条件表达式:">
                  <el-input v-model='attr["connection-form"].expr' name="expr" disabled>
                    <el-button slot="append" type="info" plain @click="conditionSelect">选择</el-button>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-footer>
      </el-container>
    </el-container>

    <!--条件表达式，添加弹出框-->
    <el-dialog :title="dialog.add.title" :visible.sync="dialog.add.formVisible" v-dialogDrag>
      <!-- ref=dlgForm用于验证表单 -->
      <el-form ref="dlgFormAdd" :model="dialog.form" size="mini">
        <el-input type="hidden" v-model="dialog.form.id" />
        <el-row>
          <!--表单-->
          <el-col :xs="24" :sm="12" :md="12">
            <!-- prop,:rules必须一起写 -->
            <el-form-item
              label="表单"
              :label-width="dialog.formLabelWidth"
              prop="exprForm"
              :rules="dialog.formRules.exprForm"
            >
              <el-select
                v-model="dialog.form.exprForm"
                placeholder="请选择表单"
                filterable
                clearable
                @change="dlg_add_exprForm_change"
              >
                <el-option
                  v-for="item in dict.exprForm"
                  :key="item.name"
                  :label="item.displayName"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--表单字段-->
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item
              label="表单字段"
              :label-width="dialog.formLabelWidth"
              prop="exprFields"
              :rules="dialog.formRules.exprFields"
            >
              <el-select
                v-model="dialog.form.exprFields"
                placeholder="请选择表单字段"
                filterable
                clearable
              >
                <el-option
                  v-for="item in dict.exprFields"
                  :key="item.name"
                  :label="item.displayName"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--字段类型-->
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item
              label="字段类型"
              :label-width="dialog.formLabelWidth"
              prop="exprType"
              :rules="dialog.formRules.exprType"
            >
              <el-select
                v-model="dialog.form.exprType"
                placeholder="请选择字段类型"
                filterable
                clearable
                @change="dlg_add_exprType_change"
              >
                <el-option
                  v-for="item in dict.exprType"
                  :key="item.key"
                  :label="item.name"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--判断条件-->
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item
              label="判断条件"
              :label-width="dialog.formLabelWidth"
              prop="exprCondition"
              :rules="dialog.formRules.exprCondition"
            >
              <el-select
                v-model="dialog.form.exprCondition"
                placeholder="请选择判断条件"
                filterable
                clearable
              >
                <el-option
                  v-for="item in dict.exprCondition"
                  :key="item.key"
                  :label="item.name"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--判断值-->
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item
              label="判断值"
              :label-width="dialog.formLabelWidth"
              prop="exprValue"
              :rules="dialog.formRules.exprValue"
            >
              <el-input v-model="dialog.form.exprValue"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="success" @click="addOk">确 定</el-button>
        <el-button type="info" plain @click="dialog.add.formVisible=false">取 消</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
  import request from '../../../utils/request'
  /* 工具类，ajax请求 */
  import * as kk from '../../../utils/k-utils'
  // dialog可以拖拽
  import '../../../utils/directives.js'

  // 表单字段只允许输入数字校验
  const validateExprValueNumber = (rule, value, callback) => {
    // 非负整数
    var regPos = /^\d+$/
    // 负整数
    var regNeg = /^\-[1-9][0-9]*$/
    if (regPos.test(value) || regNeg.test(value)) {
      callback()
    } else {
      callback(new Error('判断值必须为数字'))
    }
  }

  export default {
    name: 'FlowMgt',
    data() {
      return {
        /* 字典 */
        dict: {
          processType: {}, // 流程类型
          exprForm: [], // 表单
          exprFields: [], // 表单字段
          exprType: [], // 字段类型
          exprCondition: [] // 判断条件
        },
        form: {
          name: '', // 英文名
          displayName: '', // 中文名
          processType: '' // 流程名
        },
        // 画布
        paintStyleSelected: {
          strokeStyle: 'red',
          lineWidth: 3
        },
        paintStyle: {
          strokeStyle: '#61B7CF',
          lineWidth: 3
        },
        $canvas: {}, // jquery对象
        canvas: {}, // 画布对象
        initProcessData: {
          'nodesInfo': {
            'start': {
              'type': 'startevent-none',
              'style': 'left: 10px; top: 85px;',
              'attrCache': {
                'name': 'start'
              }
            },
            'end': {
              'type': 'endevent-none',
              'style': 'left: 339px; top: 85px;',
              'attrCache': {
                'name': 'end'
              }
            },
            'initTask': {
              'type': 'task',
              'style': 'left: 146px; top: 82px;',
              'attrCache': {
                'name': 'applyTask',
                'displayName': '申请'
              }
            }
          },
          'connectionsInfo': {
            'startConnection': {
              'from': 'start',
              'to': 'applyTask',
              'attrCache': {
                'name': 'startConnection'
              }
            },
            'endConnection': {
              'from': 'applyTask',
              'to': 'end',
              'attrCache': {
                'name': 'endConnection'
              }
            }
          }
        },
        // 属性
        attr: {
          modelShow: '', // 用于属性选择的模态框
          // 起始节点
          'startevent-none-form': {
            name: '', // 名称
            preInterceptor: '', // 前置拦截器
            postInterceptors: '' // 任务拦截器
          },
          // 结束节点
          'endevent-none-form': {
            name: '', // 名称
            preInterceptor: '', // 前置拦截器
            postInterceptors: '' // 任务拦截器
          },
          // 任务节点
          'task-form': {
            name: '', // 名称
            displayName: '' // 显示名称
          },
          // 唯一网关
          'gateway-exclusive-form': {
            name: '', // 名称
            decisionHandler: '', // 决策处理器接口
            preInterceptor: '', // 前置拦截器
            postInterceptors: '' // 任务拦截器
          },
          // 并行网关
          'gateway-fork-form': {
            name: '', // 名称
            preInterceptor: '', // 前置拦截器
            postInterceptors: '' // 任务拦截器
          },
          // 合并网关
          'gateway-join-form': {
            name: '', // 名称
            preInterceptor: '', // 前置拦截器
            postInterceptors: '' // 任务拦截器
          },
          // 连接
          'connection-form': {
            name: '', // 名称
            displayName: '', // 显示名称
            expr: '' // 条件表达式
          },
          // 校验form规则选择,动态修改
          ruleSelect: {
            name: '', // 名称
            displayName: '' // 显示名称
          },
          formRules: {
            name: [
              { required: true, message: '请输入名称', trigger: 'blur' }
            ],
            displayName: [
              { required: true, message: '请输入显示名称', trigger: 'blur' }
            ]
          }
        },
        // 弹出框
        dialog: {
          formLabelWidth: '100px',
          formRules: {
            exprForm: [
              { required: true, message: '请选择表单', trigger: 'change' }
            ],
            exprFields: [
              { required: true, message: '请选择托表单字段', trigger: 'change' }
            ],
            exprType: [
              { required: true, message: '请选择字段类型', trigger: 'change' }
            ],
            exprCondition: [
              { required: true, message: '请选择判断条件', trigger: 'change' }
            ],
            exprValue: [
              { required: true, message: '请输入判断值', trigger: 'blur' }
            ]
          },
          form: {
            exprForm: '', // 表单
            exprFields: '', // 表单字段
            exprType: '', // 字段类型
            exprCondition: '', // 判断条件
            exprValue: '' // 判断值
          },
          add: {
            title: '条件表达式',
            formVisible: false
          },
          edit: {
            title: '条件表达式',
            formVisible: false
          }
        }
      }
    },
    mounted() {
      this.init()
    },
    methods: {
      init() {
        /* 加载字典 */
        // 流程类型
        this.dict.processType = {
          '0': '普通',
          '1': '自定义'
        }
        // 字段类型
        this.dict.exprType = [
          { key: 'string', name: '字符串' },
          { key: 'number', name: '数字' }
        ]
        // 判断条件
        this.dict.exprCondition = [
          { key: '1', name: '大于', mathShow: '>' },
          { key: '2', name: '大于等于', mathShow: '>=' },
          { key: '3', name: '小于', mathShow: '<' },
          { key: '4', name: '小于等于', mathShow: '<=' },
          { key: '5', name: '等于', mathShow: '==' },
          { key: '6', name: '不等于', mathShow: '!=' }
        ]
        // 动态字典
        var _this = this
        // 表单
        kk.k_load_url('workflow', '/ctx/list/select2.json', {}).then(rep => {
          rep = JSON.parse(rep)
          _this.dict.exprForm = rep
        })
        // 创建流程
        this.createFlow()
        // 初始化流程
        this.initFlow(this.initProcessData)
      },
      // 创建流程
      createFlow() {
        var v_this = this
        // 选中connection的样式
        var processData = {
          nodesInfo: {
            '${node_name}': {
              type: 'type',
              style: 'left: 638px; top: 31px;',
              attrCache: {}
            }
          },
          connectionsInfo: {
            'transition_name': {
              from: 'node_name',
              to: 'node_name',
              attrCache: {}
            }
          }
        }
        var $canvas = $('#canvas')
        var _canvas = $canvas.Flowdesign({
          // 全局事件
          canvasMenus: {
            'save': function() {
              processData = $.parseJSON(_canvas.getProcessInfo())
              console.log(processData)
            },
            'clear': function() {
              _canvas.clear()
            },
            'refresh': function() {
              _canvas.clear()
              _canvas.refresh(processData)
            }
          },
          // 连接线的菜单事件
          connectionMenus: {
            menus: {
              'delete': '删除'
            },
            'delete': function(connection) {
              _canvas.deleteConnection(connection)
            }
          },
          // 步骤右键
          processMenus: {
            menus: {
              'delete': '删除'
            },
            'delete': function(process) {
              _canvas.deleteProcess(process)
            }
          },
          fnClick: function() {
            // $attrPanelForm.find('input').trigger('blur')
            var $this = $(this)
            var nodeSelected = $this.hasClass('process-node-select')
            v_this.clearSelectedStyle()
            v_this.$refs['attrForm'].clearValidate() // 清除校验规则
            if (!nodeSelected) {
              $this.addClass('process-node-select')
              var processType = $this.attr('process-type')
              v_this.attr.ruleSelect = v_this.attr[processType + '-form'] // 校验form选择
              v_this.attr.modelShow = processType// 显示内容
              var attrCache = $.extend({}, ($this.data('attrCache') || window.defaultComponentAttr[processType]))
              // 使用默认值
              v_this.copyObj(attrCache, v_this.attr[processType + '-form'])
              if (processType === 'task') {
                // handleTaskNodeAttrCache(attrCache)
                // // 初始化表单select
                // initFormSelect(attrCache.formId)
                // initActorSqlSelect(attrCache.actorSql)
                // initEnableAttachmentSelect(attrCache.enableAttachment || '0')// 默认不启用附件上传
                // initUseRoleSelect(attrCache.useRole || '1')//默认值为启用
              }
            } else {
              v_this.attr.modelShow = '' // 不显示属性内容
            }
          },
          fnConnectionClick: function(connection, originalEvent) {
            var connectionSelected = (connection.getPaintStyle().strokeStyle === v_this.paintStyleSelected.strokeStyle)
            v_this.clearSelectedStyle()
            v_this.$refs['attrForm'].clearValidate() // 清除校验规则
            // true当前为选中，设置其为不选中
            if (connectionSelected) {
              v_this.attr.modelShow = '' // 不显示属性内容
              connection.setPaintStyle(v_this.paintStyle)
            } else {
              v_this.attr.ruleSelect = v_this.attr['connection-form'] // 校验form选择
              v_this.attr.modelShow = 'connection' // 显示属性内容
              v_this.canvas.refreshConnectionDefaultname(connection)
              var attrCache = $.extend({}, (connection.getData() || window.defaultComponentAttr['connection']))
              v_this.copyObj(attrCache, v_this.attr['connection-form'])
              connection.setPaintStyle(v_this.paintStyleSelected)
            }
          },
          paintStyle: this.paintStyle
        })
        this.$canvas = $canvas
        this.canvas = _canvas
        // 允许拖拽
        $('.icon-list').draggable({
          zIndex: 1,
          cursor: 'move',
          helper: 'clone'
        })
        // 接受拖拽物
        $canvas.droppable({
          activeClass: 'ui-state-default',
          hoverClass: 'ui-state-hover',
          accept: ':not(.ui-sortable-helper)',
          drop: function(ev, ui) {
            var top = ui.offset.top
            top = top - $(this).offset().top + $canvas.scrollTop()
            var left = ui.offset.left
            left = left - $(this).offset().left + $canvas.scrollLeft()
            var type = ui.helper[0].attributes['process-type'].nodeValue
            var style = 'left: ' + left + 'px; top: ' + top + 'px;'
            // 添加节点
            _canvas.addProcess(type, style)
          }
        })
        // 属性初始化
        this.attrInit()
      },
      // 属性初始化
      attrInit() {
        var v_this = this
        $('.attr-footer').on('change', 'input', function() {
          var $this = $(this)
          // 校验表单数据
          v_this.$refs.attrForm.validate((valid) => {
            if (valid) {
              v_this.attrInputChange($this)
            } else {
              console.log('表单数据检验没有全部通过！！')
            }
          })
        })
      },
      // 属性输入框改变
      attrInputChange(inputThis) {
        var $this = $(inputThis)
        var $selectedNode = this.$canvas.find('.process-node-select')
        var processType = $selectedNode.attr('process-type')
        var name = $this.attr('name')
        var attrCache
        if ($selectedNode.length !== 0) {
          attrCache = $.extend({}, ($selectedNode.data('attrCache') || window.defaultComponentAttr[processType]))
          // 处理特殊的元素, 该元素是针对,按钮，角色，人员选择的
          // 给它带上前缀
          if (name === 'actors' || name === 'roles' || name === 'btns' || name === 'fields' || name === 'rejectTaskNames' || name === 'detailFields') {
            attrCache[name + '-checkedKeys'] = $this.attr('data-checked-keys')
            attrCache[name + '-checkedValues'] = $this.attr('data-checked-values')
          } else {
            // 普通输入框
            attrCache[name] = this.attr[processType + '-form'][name]
          }
          $selectedNode.data('attrCache', attrCache)
          // 节点显示名称
          this.handleSelectedNodeLabelDisplay($selectedNode, attrCache)
        } else {
          // 这个选中的是connection
          var connection = this.canvas.getSelectedConnection()
          attrCache = $.extend({}, (connection.getData() || window.defaultComponentAttr['connection']))
          attrCache[name] = this.attr['connection-form'][name]
          connection.setData(attrCache)// 给连接设置额外的属性缓存
          var displayName = attrCache['displayName']
          // 在连接上面设置标签
          if (displayName) {
            connection.setLabel(displayName)
            connection.getLabelOverlay().addClass('connection-label')
          } else {
            connection.setLabel({ label: ' ' })
            connection.getLabelOverlay().removeClass('connection-label')
          }
        }
      },
      // 节点显示名称
      handleSelectedNodeLabelDisplay($selectedNode, attrCache) {
        var processType = $selectedNode.attr('process-type')
        switch (processType) {
        case 'task':
          $selectedNode.find('.task-inner-text').text(attrCache['displayName'])
          break
        default:
        }
      },
      // 清除节点选中样式
      clearSelectedStyle() {
        var connectionSelected = this.canvas.getSelectedConnection()
        this.$canvas.find('.process-node').removeClass('process-node-select')
        if (connectionSelected) {
          connectionSelected.setPaintStyle(this.paintStyle)
        }
      },
      // 初始化设计器按钮触发
      initDesignBtn() {
        // 初始化流程
        this.initFlow(this.initProcessData)
      },
      // 初始化设计器内容
      initFlow(processData) {
        processData = $.type(processData) === 'string' ? $.parseJSON(processData) : processData
        this.canvas.clear()
        this.canvas.refresh(processData)
      },
      // --------------------------------属性--------------------------------
      // 条件选择
      conditionSelect() {
        // 清空数据
        this.copyObj({
          exprForm: '', // 表单
          exprFields: '', // 表单字段
          exprType: '', // 字段类型
          exprCondition: '', // 判断条件
          exprValue: '' // 判断值
        }, this.dialog.form)
        this.$nextTick(() => {
          // 重复新增，去掉校验提示
          this.$refs.dlgFormAdd.clearValidate() // 必须写在$nextTick里面
        })
        this.dialog.add.formVisible = true
        // 改变校验规则
        this.dialog.formRules.exprValue = [
          { required: true, message: '请输入判断值', trigger: 'blur' }
        ]
      },
      // --------------------------------弹出框--------------------------------
      // 表单内容变化
      dlg_add_exprForm_change(val) {
        if (val === '') {
          // 清空
          this.dialog.form.exprFields = ''// 表单字段
          return
        }
        // 从字典中找到自己对应的数据
        var item = null
        for (var i = 0; i < this.dict.exprForm.length; i++) {
          if (this.dict.exprForm[i].name === val) {
            item = this.dict.exprForm[i]
            break
          }
        }
        if (item == null) {
          return
        }
        var fieldData = JSON.parse(item.json)
        // 加载表单字段
        this.dict.exprFields = fieldData.fieldsConf
        this.dialog.form.exprFields = ''// 清除数据
      },
      // 字段类型变化
      dlg_add_exprType_change(val) {
        if (val === '') {
          return
        }
        // 改变校验规则
        if (val === 'string') {
          this.dialog.formRules.exprValue = [
            { required: true, message: '请输入判断值', trigger: 'blur' }
          ]
        } else {
          this.dialog.formRules.exprValue = [
            { required: true, message: '请输入判断值', trigger: 'blur' },
            { validator: validateExprValueNumber, trigger: 'blur' }
          ]
        }
      },
      // 新增确认
      addOk() {
        var _this = this
        this.$refs.dlgFormAdd.validate((valid) => {
          if (valid) {
            _this.addOkHandler()
          } else {
            console.log('表单数据检验没有全部通过！！')
          }
        })
      },
      addOkHandler() {
        // 获取全局对象数据
        var bean = this.dialog.form
        var _this = this
        // 关闭弹出框
        _this.dialog.add.formVisible = false
        // 保存数据
        this.addOkHandlerData()
      },
      // 保存数据
      addOkHandlerData() {
        var bean = this.dialog.form
        // 组装结果
        var showExpr = this.findWhere(this.dict.exprForm, { name: bean.exprForm }).displayName
        showExpr += this.findWhere(this.dict.exprCondition, { key: bean.exprCondition }).mathShow
        showExpr += bean.exprValue
        var result = {
          'exprFormId': bean.exprForm, // 表单
          'exprType': bean.exprType, // 字段类型
          'exprKey': bean.exprFields, // 表单字段
          'exprValue': bean.exprValue, // 判断值
          'exprCondition': bean.exprCondition, // 判断条件
          'showExpr': showExpr
        }
        this.attr.form.expr = showExpr
        // 获取选中连接，并缓存数据
        var connection = this.canvas.getSelectedConnection()
        var attrCache = $.extend({}, (connection.getData() || window.defaultComponentAttr['connection']), result)
        // 给连接设置额外的属性缓存
        connection.setData(attrCache)
      },
      // --------------------------------公共函数--------------------------------
      // 将obj1对象的数据拷贝到obj2对象
      copyObj(obj1, obj2) {
        for (var key in obj1) {
          // 原型对象不拷贝
          if (key === '__proto__') {
            continue
          }
          // 自动将number转换成string
          if (typeof obj1[key] === 'number') {
            obj1[key] = '' + obj1[key]
          }
          obj2[key] = obj1[key]
        }
      },
      // 数组通过属性查找 例如 arr = [obj,obj]
      findWhere(arr, obj) {
        for (var i = 0; i < arr.length; i++) {
          for (var key in obj) {
            // key相等,value也相等
            if (arr[i].hasOwnProperty(key) && arr[i][key] === obj[key]) {
              return arr[i]
            }
          }
        }
        return {}
      },
      // --------------------------------保存--------------------------------
      addBean() {
        // 获取头部数据并校验，不添加form校验了免得麻烦
        if (!this.form.name) {
          this.$message({ message: '流程英文名不能为空', type: 'warning', showClose: true })
          return false
        }
        if (!this.form.displayName) {
          this.$message({ message: '流程中文名不能为空', type: 'warning', showClose: true })
          return false
        }
        if (!(this.form.processType === '1' || this.form.processType === '0')) {
          this.$message({ message: '流程类型不能为空', type: 'warning', showClose: true })
          return false
        }
        // 保存数据处理
        this.addBeanHandler()
      },
      // 保存数据处理
      addBeanHandler() {
        var processData = {}
        // 给流程数据增加中文名和英文名以及上下文
        processData.name = this.form.name
        processData.displayName = this.form.displayName
        var processInfo = JSON.parse(this.canvas.getProcessInfo())
        $.extend(true, processData, processInfo)
        // 新增流程
        this.addFlowAjax(processData)
      },
      // 新增流程
      addFlowAjax(processData, contextId, processType) {
        var params = {
          processData: JSON.stringify(processData), // 流程数据
          contextId: contextId,
          processType: this.form.processType // 流程类型
        }
        var _this = this
        var url = '/workflow/process/flow.json'
        request({
          loading: true,
          url: url,
          method: 'post',
          params: params
        }).then(rep => {
          rep = JSON.parse(rep)
          if (rep['status'] === '200') {
            _this.$message({ message: '保存成功,需要发布流程,流程才可生效', type: 'success', showClose: true })
            kk.k_close_self_page()
          } else {
            _this.$message({ message: rep.message, type: 'warning', showClose: true })
          }
        })
      }
    }
  }
</script>

<style>
  /* 引入样式 */
  @import '../../../../public/css/workflow/kayakwiseflowdesign.css';
</style>
<style scoped>
  .home {
    -moz-user-select: text; /*火狐*/
    -webkit-user-select: text; /*webkit浏览器*/
    -ms-user-select: text; /*IE10*/
    -khtml-user-select: text; /*早期浏览器*/
    user-select: text;
    font: normal 12px courier;
    font-family: 'Microsoft Yahei', verdana;
    background: none;
    overflow: auto;
  }
  .headerRow {
    border-radius: 0px;
    outline: 0;
    border: 1px solid #C8C8C8;
    margin-top: 0px;
    box-shadow: 0 0 0;
    background: #fafafa;
  }
  .activityRow {
    color: #666;
    background-image: linear-gradient(to bottom,#f5f5f5 0,#e8e8e8 100%);
    background-repeat: repeat-x;
    background-color: #f5f5f5;
    height: 25px;
    line-height: 25px;
    border-left: 1px solid #C8C8C8;
    border-right: 1px solid #C8C8C8;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
  }
  .attr-row-class {
    padding: 15px;
    color: rgb(85, 85, 85);
  }
  .not_pre{
    display: none;
  }

  .icon-list {
    width: 150px;
    height: 32px;
    background-size: 32px 32px;
    font-size: 14px;
  }

  .searchName:after {
    content: ":";
  }

  .margin-top-bottom-10 {
    margin-top: 10px;
    margin-bottom: 10px;
  }

  .showLabelDiv {
    margin-bottom: 10px;
  }

  .form-control {
    padding-top: 0;
    padding-bottom: 0;
  }

  #attr-form input, select {
    height: 24px;
    font-size: 12px !important;
  }

  #attr-form .col-sm-4 {
    width: 250px;
    padding-left: 0;
    padding-right: 0;
  }

  #flow_display_name, #flow_name {
    height: 24px;
    font-size: 12px !important;
  }

  label.top3-right0 {
    padding-top: 3px !important;
    padding-right: 0;
  }

  .formFieldSelect .select2-selection__placeholder, .select2-selection__rendered {
    height: auto;
  }

  #select-modal input {
    height: 24px;
  }

  #expr-modal td, #expr-modal .modal-title {
    font-size: 12px !important;
  }
</style>
